//
//  VRBindDeviceViewController.m
//  VRFirefighting
//
//  Created by Veer on 2018/8/19.
//  Copyright © 2018年 Veer. All rights reserved.
//

#import "VRBindDeviceViewController.h"
#import "XScanViewController.h"

#import "VRBindDeviceCell.h"
#import "XDropMenuView.h"
#import "JKSelectorView.h"
#import "JKPersonInfoConfigModel.h"


@interface VRBindDeviceViewController () <UITableViewDataSource, UITableViewDelegate, XDropMenuViewDelegate, XScanViewControllerDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) XDropMenuView *dropMenu;



@property (nonatomic, weak) UITextField *curSelectedTextFeild;
@property (nonatomic, strong) NSIndexPath *curSelectedIndexPath;

@property (nonatomic, weak) UITextField *captchaTextFeild;

@property (nonatomic, strong) NSMutableDictionary<NSString *, NSArray<JKPersonInfoConfigModel *> *> *configureDict;
@property (nonatomic, strong) NSArray<JKPersonInfoConfigModel *> *configureModelArray;
@property (nonatomic, copy) NSString *curSelectedKey;
@property (nonatomic, copy) NSString *class0;

@end

@implementation VRBindDeviceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = ScrollViewBgColor;
    self.title = @"绑定设备";
    
    [self setupSubView];
    [self setupListMenu];
}

- (void)setupSubView
{
    [self.view addSubview:self.tableView];
    
    UIView *footerView = [[UIView alloc] init];
    footerView.frame = CGRectMake(0, 0, kScreenWidth, 104);
    self.tableView.tableFooterView = footerView;
    
    // 按钮
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    loginBtn.backgroundColor = RGB(78, 173, 57);
    loginBtn.layer.cornerRadius = 4;
    [loginBtn setTitle:@"完成绑定" forState:UIControlStateNormal];
    loginBtn.titleLabel.font = VRFont(16);
    [loginBtn setTitleColor:RGB(255, 255, 255) forState:UIControlStateNormal];
    [loginBtn setTitleColor:RGB(120, 120, 120) forState:UIControlStateHighlighted];
    [loginBtn addTarget:self action:@selector(onSaveBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:loginBtn];
    [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(footerView);
        make.centerY.mas_equalTo(footerView);
        make.width.mas_equalTo(kScreenWidth - 36 * 2);
        make.height.mas_equalTo(44);
    }];
}


- (void)setupListMenu
{
    
    NSArray *imgNameArray = @[@"equipment_001", @"equipment_003", @"equipment_005", @"equipment_004", @""];
    
    UIView *listBgView = [[UIView alloc] init];
//    listBgView.backgroundColor = RGB(255, 255, 255);
    listBgView.frame = CGRectMake(0, NAVIGATION_BAR_HEIGHT, kScreenWidth, 200);
//    [self.view addSubview:listBgView];
    self.tableView.tableHeaderView = listBgView;
    
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    imageView.image = [UIImage imageNamed:imgNameArray[self.type]];
    imageView.frame = CGRectMake(0, 20, 118, 118);
    imageView.centerX = kScreenWidth * 0.5;
    [listBgView addSubview:imageView];
    
    UIView *listView = [[UIView alloc] init];
    listView.backgroundColor = RGB(255, 255, 255);
    listView.layer.borderColor = MAINColor.CGColor;
    listView.layer.borderWidth = 1.0;
    listView.frame = CGRectMake(0, 160, kScreenWidth - 20 * 2, 40);
    listView.centerX = kScreenWidth * 0.5;
    [listBgView addSubview:listView];
    
    UILabel *detailLbl = [[UILabel alloc] init];
    detailLbl.text = @"请选择传输类型";
    detailLbl.textColor = RGB(80, 80, 80);
    detailLbl.font = VRFont(14);
    //    detailLbl.textAlignment = NSTextAlignmentRight;
    detailLbl.frame = CGRectMake(8, 0, 100, 40);
    [listView addSubview:detailLbl];
    
    //列表展示的模型
    NSMutableArray *section1Datas = [NSMutableArray array];
    
    NSArray *title1Array = self.configureDict.allKeys;
    for (NSString *str in title1Array) {
        XMenuModel *model = [[XMenuModel alloc] init];
        model.name = str;
        model.id = str;
        [section1Datas addObject:model];
    }
    
    NSMutableArray *allDatas = [NSMutableArray array];
    [allDatas addObject:section1Datas];
    
    //上边按钮展示的模型,此模型对text赋值即可.
    NSArray *titleArray = @[@"全部分类"];
    
    //若列表展示内容与按钮展示内容相同则showArr传nil即可。
    XDropMenuView *dropMenu = [[XDropMenuView alloc] initWithFrame:CGRectMake(0, 0, listView.width, 40) showOnView:self.view AllDataArr:allDatas showArr:[titleArray copy]];
    dropMenu.itemNormalColor = MAINColor;
    dropMenu.itemSelectedColor = MAINColor;
    dropMenu.titleNormalColor = MAINColor;
    dropMenu.titleSelectedColor = MAINColor;
    dropMenu.fonteSize = 14;
    dropMenu.delegate = self;
    [listView addSubview:dropMenu];
    self.dropMenu = dropMenu;
    
    [dropMenu selectClum:0 Row:0];
    self.class0 = [title1Array firstObject];
    //    NSInteger index = self.curSelectBallIndex - 1;
    //    if (index >= 0 && index < DropMenuTitle0.count) {
    //
    //
    //    }else{
    //
    //        [dropMenu selectClum:0 Row:0];
    //        self.class1 = DropMenuTitle1[0][@"param"];
    //    }
    //
    //    [dropMenu selectClum:1 Row:0];
    //    self.class0 = DropMenuTitle0[0][@"param"];
    
}

- (void)showScan
{
//    XScanViewController *scanVc = [[XScanViewController alloc] init];
//    scanVc.delegate = self;
//    [self.navigationController pushViewController:scanVc animated:YES];
    XScanViewController *authVc = [[XScanViewController alloc] init];
    authVc.delegate = self;
    [self presentViewController:authVc animated:YES completion:nil];
}

- (void)changeType
{
    if ([self.class0 isEqualToString:@"GSM"]) {
        
        NSArray<JKPersonInfoConfigModel *> *configureModelArray = self.configureDict[@"NB-IOT"];
        
        self.configureModelArray[0].value = configureModelArray[0].value;
        self.configureModelArray[1].value = configureModelArray[1].value;
        self.configureModelArray[2].value = configureModelArray[2].value;
        self.configureModelArray[4].value = configureModelArray[3].value;
    }else{
        
        NSArray<JKPersonInfoConfigModel *> *configureModelArray = self.configureDict[@"GSM"];
        
        self.configureModelArray[0].value = configureModelArray[0].value;
        self.configureModelArray[1].value = configureModelArray[1].value;
        self.configureModelArray[2].value = configureModelArray[2].value;
        self.configureModelArray[3].value = configureModelArray[4].value;
    }
}

- (void)clearValue
{
    NSArray<JKPersonInfoConfigModel *> *configureModelArray = self.configureDict[@"GSM"];
    NSArray<JKPersonInfoConfigModel *> *configureModelArray1 = self.configureDict[@"NB-IOT"];
    for (JKPersonInfoConfigModel *model in configureModelArray) {
        model.value = nil;
    }
    for (JKPersonInfoConfigModel *model in configureModelArray1) {
        model.value = nil;
    }
    [self.tableView reloadData];
}

#pragma mark - networkign
- (void)saveDeviceInfo
{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userID"] = [VRUser shareUser].token;
    param[@"alias"] = self.configureModelArray[0].value;
    param[@"model"] = self.configureModelArray[1].value;
    param[@"site"] = self.configureModelArray[2].value;
    param[@"fEntityFacilityID"] = self.configureModelArray[3].value;
    if ([self.class0 isEqualToString:@"GSM"]) {
        param[@"fEntityGetwayID"] = self.configureModelArray[4].value;
    }else{
        param[@"fEntityGetwayID"] = @"123456";
    }
    
    param[@"typeName"] = self.class0;
    param[@"type"] = @(self.type);
    
    weakify(self)
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [JKNetworking postWithSign:BindDevice1 parameters:param success:^(NSDictionary *responseObject) {
        
        strongify(self)
        NSLog(@"responseObject:%@", responseObject);
        NSInteger code = [responseObject[@"state"] integerValue];
        NSString *msg = responseObject[@"message"];
        
        if (code == 0) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [hud hideAnimated:YES];
                [SVProgressHUD showSuccessWithStatus:@"保存成功"];
                [self clearValue];
            });
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
//                [self.navigationController popViewControllerAnimated:YES];
            });
            
        }else if(msg.length > 0){
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:msg];
                [hud hideAnimated:YES];
            });
        }
    } error:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:@"未知错误"];
            [hud hideAnimated:YES];
        });
    }];
}


#pragma mark - action
- (void)onSaveBtnClick:(UIButton *)sender
{
    for (JKPersonInfoConfigModel *model in self.configureModelArray) {
        
        if (model.value.length == 0) {
            
            NSString *name = model.name;
            name = [name stringByReplacingOccurrencesOfString:@"：" withString:@""];
            NSString *msg = [NSString stringWithFormat:@"%@不能为空", name];
            [SVProgressHUD showErrorWithStatus:msg];
            return;
        }
    }
    
//    [SVProgressHUD showErrorWithStatus:@"绑定失败，请稍后重试"];
    [self saveDeviceInfo];
}

#pragma mark - delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{

    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.configureModelArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 66;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JKPersonInfoConfigModel *model = self.configureModelArray[indexPath.row];
    
    VRBindDeviceCell *cell = [VRBindDeviceCell cellWith:tableView];
    cell.model = model;
    
    weakify(self)
    cell.textFieldClickBlock = ^(UITextField *textField) {
        
        strongify(self)
        
        self.curSelectedTextFeild = textField;
        self.curSelectedIndexPath = indexPath;
        
        //        if (indexPath.section == 1 && indexPath.row == 0) {
        //
        //            [self.view endEditing:YES];
        //            [self.areaSelectorView show];
        //            return;
        //        }
        
        if (!model.isCanEdit) {
            [self.view endEditing:YES];
        }
        
        if (model.performName.length > 0) {
            
            [self.view endEditing:YES];
//            if ([self respondsToSelector:NSSelectorFromString(model.performName)]) {
//                
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    [self performSelector:NSSelectorFromString(model.performName) withObject:nil];
//                });
//            }
        }
    };
    
    cell.scanClickBlock = ^{
        strongify(self)
        [self showScan];
    };
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    JKPersonInfoConfigModel *model = self.configureModelArray[indexPath.row];
}

#pragma mark - XDropMenuViewDelegate
- (void)dropMenuView:(XDropMenuView *)dropMenuView didSelectColum:(NSInteger)colum
{
    [self.view endEditing:YES];
    NSLog(@"dropMenuView:%d", (int)colum);
}

- (void)dropMenuView:(XDropMenuView *)dropMenuView didSelectRowAtColum:(NSInteger)colum Row:(NSInteger)row model:(XMenuModel *)model
{
    NSLog(@"class0:%@", model.id);
    self.class0 = model.id;
    self.curSelectedKey = model.name;
    [self changeType];
    [self.tableView reloadData];
}

#pragma mark - XScanViewControllerDelegate
- (void)getScanResultxxxxxxxxxxx:(NSString *)stringValue
{
    self.configureModelArray[3].value = stringValue;
    self.curSelectedTextFeild.text = stringValue;
}

#pragma mark - lazy
- (UITableView *)tableView
{
    if (_tableView == nil) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.backgroundColor = ScrollViewBgColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 0.01)];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.sectionHeaderHeight = 0;
        _tableView.sectionFooterHeight = 0;
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        [self.view addSubview:self.tableView];
        [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(self.view);
            make.top.mas_equalTo(0);
            make.bottom.mas_equalTo(0);
        }];
        
        
        UIView *headerView = [[UIView alloc] init];
        headerView.frame = CGRectMake(0, 0, kScreenWidth, 20);
        
        //        UIImageView *topImgView = [[UIImageView alloc] init];
        //        topImgView.contentMode = UIViewContentModeScaleAspectFit;
        //        topImgView.image = [UIImage imageNamed:@"icon_base_info"];
        //        topImgView.frame = CGRectMake(0, 16, kScreenWidth, 112 - 16);
        //        [headerView addSubview:topImgView];
        
        _tableView.tableHeaderView = headerView;
    }
    return _tableView;
}

- (NSArray<JKPersonInfoConfigModel *> *)configureModelArray
{
    NSString *key = self.curSelectedKey;
    if (self.curSelectedKey.length == 0) {
        key = @"GSM";
    }
    _configureModelArray = self.configureDict[key];
    return _configureModelArray;
}

- (NSMutableDictionary<NSString *, NSArray<JKPersonInfoConfigModel *> *> *)configureDict
{
    if (_configureDict == nil) {
        
        _configureDict = [NSMutableDictionary dictionary];
        
        NSString *path =  [[NSBundle mainBundle] pathForResource:@"VRBindDevice" ofType:@"plist"];
        NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
        for (NSString *key in dict.allKeys) {
            
            NSArray<JKPersonInfoConfigModel *> *arry = [NSMutableArray arrayWithArray:[JKPersonInfoConfigModel mj_objectArrayWithKeyValuesArray:dict[key]]];
            _configureDict[key] = arry;
        }
    }
    return _configureDict;
}

@end
